#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef double db;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout);
#define pb push_back

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int N = 5e4+10;

struct node{int u,v,w;};
bool operator < (node a,node b){return a.w < b.w;}
vector<node> e,f;
int n,m,need,fa[N],ud,cost;

int gf(int x){return fa[x] == x ? x : fa[x] = gf(fa[x]);}

bool add(node t,int c = 0){
	int fx = gf(t.u),fy = gf(t.v);
	if(fx ^ fy) return fa[fx] = fy,cost += t.w + c,1;
	return 0;
}

void gettree(int mid){
	for(int i = 0;i < n;i++) fa[i] = i;
	int c1 = e.size(),c2 = f.size(),i = 0,j = 0; ud = 0; cost = 0;
	for(;i < c1 && j < c2;){
		if(e[i].w + mid < f[j].w) {
			if(add(e[i],mid)) ud++; i++;
		}else add(f[j]),j++;
	}
	for(;i < c1;i++) if(add(e[i],mid)) ud++;
	for(;j < c2;j++) add(f[j]);
}

int main (){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	n = in,m = in,need = in;
	for(int i = 1;i <= m;i++){
		int u = in,v = in,w = in,col = in;
		if(col == 0) e.pb((node){u,v,w});
		else f.pb((node){u,v,w});
	}
	sort(e.begin(),e.end()); sort(f.begin(),f.end());
	int l = -110,r = 110;
	while(l <= r){
		int mid = l + r >> 1;
		gettree(mid);
		if(ud >= need) l = mid + 1;
		else r = mid - 1;
	}gettree(l);//cerr<<l<<".."<<ud<<endl;
	printf("%d\n",cost - l * need);
	return 0;
}

